package com.bigtotoro.shuiyincamera;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.MainThread;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigtotoro.shuiyincamera.csj.TTAdManagerHolder;
import com.bigtotoro.shuiyincamera.csj.WeakHandler;
import com.bigtotoro.shuiyincamera.editimage.EditImageActivity;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.SharedPreferencesUtil;
import com.bigtotoro.shuiyincamera.video.view.MusicCropView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.luck.picture.lib.photoview.PhotoView;
import com.umeng.analytics.MobclickAgent;

import org.litepal.LitePal;

import java.io.File;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.Constant.CURRENT_CHANNEL;

public class ShowMyArtsActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "ShowMyArtsActivity";
    private PhotoView imgView;
    private VideoView videoView;
    private String type;
    private String mode;//预览模式，从列表进入预览，不显示标题文字，底部显示删除和分享
    private TextView tv_title;
    private ImageView btn_delete,btn_share;
    private ImageView iv_photo;
    private MediaPlayer mMediaPlayer;
    private View layout02;
    private ImageView iv_video_click;

    private String create_time;

    private FrameLayout mSplashContainer; //加载广告的父布局
    private String current_channel = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_my_arts);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

        if (SharedPreferencesUtil.getInstance(this).getSP(CURRENT_CHANNEL)!=null){
            current_channel =  SharedPreferencesUtil.getInstance(this).getSP(CURRENT_CHANNEL);
            Log.i(TAG, "current_channel===" + current_channel);
        }

        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mSplashContainer = (FrameLayout) findViewById(R.id.splash_container);
        initView();

//        loadSplashAd(current_channel);
    }
    private TTAdNative mTTAdNative;
    //开屏广告是否已经加载
    private TTNativeExpressAd mTTAd;
    private long startTime = 0;
    private boolean mHasShowDownloadActive = false;
//    private void loadSplashAd(String current_channel) {
//        Log.i(TAG, "current_channel===" + current_channel);
//        if (current_channel ==null|| current_channel.length() ==0)return;
//        String post_id ;
//        switch (current_channel){
//            case "dev":
//                post_id = Constant.CSJ_POSTID_SHOW_MY_ART;
//                break;
//            default:
//                post_id = "";
//                break;
//        }
//        Log.i(TAG, "post_id===" + post_id);
//        if (post_id == null || post_id.length() ==0)return;
//
//        Log.i(TAG, "加载弹窗广告" + System.currentTimeMillis());
//        mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
//        //step3:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
//        TTAdManagerHolder.get().requestPermissionIfNecessary(this);
//
//        AdSlot adSlot = new AdSlot.Builder()
////                .setCodeId(Constant.CSJ_POSTID_SHOW_MY_ART) //广告位id
//                .setCodeId(post_id) //广告位id
//                .setSupportDeepLink(true)
//                .setAdCount(1) //请求广告数量为1到3条
//                .setExpressViewAcceptedSize(270, 180) //期望个性化模板广告view的size,单位dp
////                .setImageAcceptedSize(450,300 )//这个参数设置即可，不影响个性化模板广告的size
//                .build();
//
//        //加载广告
//        mTTAdNative.loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
//            @Override
//            public void onError(int code, String message) {
//                Log.i(TAG, "加载弹窗广告 onError===" + System.currentTimeMillis());
////                TToast.show(InteractionExpressActivity.this, "load error : " + code + ", " + message);
//            }
//
//            @Override
//            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
//                if (ads == null || ads.size() == 0) {
//                    return;
//                }
//                Log.i(TAG, "加载弹窗广告 onNativeExpressAdLoad===" + System.currentTimeMillis());
//                mTTAd = ads.get(0);
//                bindAdListener(mTTAd);
//                startTime = System.currentTimeMillis();
//                mTTAd.render();
//            }
//        });
//
//    }

    private void bindAdListener(TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
            @Override
            public void onAdDismiss() {
                Log.i(TAG, "广告关闭===" + System.currentTimeMillis());
//                TToast.show(mContext, "广告关闭");
            }

            @Override
            public void onAdClicked(View view, int type) {
                Log.i(TAG, "广告被点击===" + System.currentTimeMillis());
//                TToast.show(mContext, "广告被点击");
            }

            @Override
            public void onAdShow(View view, int type) {
                Log.i(TAG, "广告展示===" + System.currentTimeMillis());
//                TToast.show(mContext, "广告展示");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                Log.i(TAG, "onRenderFail===" + System.currentTimeMillis());
//                Log.e("ExpressView", "render fail:" + (System.currentTimeMillis() - startTime));
//                TToast.show(mContext, msg + " code:" + code);
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                Log.i(TAG, "渲染成功===" + System.currentTimeMillis());
//                Log.e("ExpressView", "render suc:" + (System.currentTimeMillis() - startTime));
                //返回view的宽高 单位 dp
//                TToast.show(mContext, "渲染成功");
                mTTAd.showInteractionExpressAd(ShowMyArtsActivity.this);

            }
        });

        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
//                TToast.show(InteractionExpressActivity.this, "点击开始下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                if (!mHasShowDownloadActive) {
                    mHasShowDownloadActive = true;
//                    TToast.show(InteractionExpressActivity.this, "下载中，点击暂停", Toast.LENGTH_LONG);
                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "下载暂停，点击继续", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "下载失败，点击重新下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onInstalled(String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "安装完成，点击图片打开", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "点击安装", Toast.LENGTH_LONG);
            }
        });
    }


    private TextView tv_art_list;
    private String currentPath;
    private int videoHeight,videoWidth,videoDuration;
    private int position = 0;
    private void initView() {
        iv_video_click = findViewById(R.id.iv_video_click);
        layout02 = findViewById(R.id.layout02);
        layout02.setOnClickListener(this);
        iv_photo = findViewById(R.id.iv_photo);
        iv_photo.setOnClickListener(this);
        btn_delete = findViewById(R.id.btn_delete);
        btn_share = findViewById(R.id.btn_share);
        btn_delete.setOnClickListener(this);
        btn_share.setOnClickListener(this);
        imgView = findViewById(R.id.img);
        videoView =  findViewById(R.id.video);
        tv_title =  findViewById(R.id.tv_title);

        tv_art_list = findViewById(R.id.tv_art_list);
        tv_art_list.setOnClickListener(this);
        Intent data = getIntent();

        if (getIntent().getStringExtra("create_time")!=null){
            create_time = getIntent().getStringExtra("create_time");
        }
        if (data.getStringExtra("type")!=null){
            type = data.getStringExtra("type");
            mode = data.getStringExtra("mode");
            if (data.getIntExtra("position",-1)!=-1){
                position = data.getIntExtra("position",-1);
            }

            if (mode!=null && mode.equals("myartlist")){
                //改变UI
                tv_title.setVisibility(View.GONE);
                tv_art_list.setVisibility(View.GONE);

            }else {
                tv_title.setVisibility(View.VISIBLE);
                tv_art_list.setVisibility(View.VISIBLE);
            }
            if (type.equals("0")){ //加载图片
                imgView.setVisibility(View.VISIBLE);
                layout02.setVisibility(View.GONE);
                iv_photo.setVisibility(View.GONE);
                handleEditorImage(data);
            }else if (type.equals("1")){ //加载视频
                imgView.setVisibility(View.GONE);
                layout02.setVisibility(View.VISIBLE);
                iv_photo.setVisibility(View.GONE);

                currentPath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT);
                videoWidth =  data.getIntExtra("width",-1);
                videoHeight =  data.getIntExtra("height",-1);

                videoView.setVideoURI(Uri.parse(currentPath));
                videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        videoWidth = mediaPlayer.getVideoWidth();
                        videoHeight = mediaPlayer.getVideoHeight();
                        videoDuration = mediaPlayer.getDuration();
                        Log.d("main", "setOnPreparedListener duration "+videoDuration);

                        videoView.start();
                        mediaPlayer.setLooping(true); //循环播放
                    }
                });



            }else if (type.equals("2")){ //播放音频
                imgView.setVisibility(View.GONE);
                layout02.setVisibility(View.GONE);
                iv_photo.setVisibility(View.VISIBLE);

                currentPath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT);
                iv_photo.post(new Runnable() { //防止被广告打断音频播放
                    @Override
                    public void run() {
                        initMediaPlayer();
                    }
                });

            }
        }

    }

    private void initMediaPlayer() {
        Log.i(TAG, "initMediaPlayer ===" + System.currentTimeMillis());
        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(ShowMyArtsActivity.this, Uri.parse(currentPath)); //加载音乐
            Log.i(TAG, "initMediaPlayer currentPath ===" +currentPath);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.i(TAG, "initMediaPlayer onPrepared ===" + System.currentTimeMillis());
                    mMediaPlayer.start();
                    mMediaPlayer.setLooping(true);//循环播放

                    playCDAni();
                }
            });
        } catch (Exception e) {
            Log.i(TAG, "initMediaPlayer Exception ===" +currentPath);
            e.printStackTrace();
        }
    }


    private int imageHeight,imageWidth;

    private Bitmap mainBitmap;
    private void handleEditorImage(Intent data) {
        currentPath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT);
        imageWidth =  data.getIntExtra("width",-1);
        imageHeight =  data.getIntExtra("height",-1);
        if (currentPath!=null && currentPath.lastIndexOf(".gif")>0){
            Glide.with(ShowMyArtsActivity.this).load(new File(currentPath)).into(imgView);
        }else {
            LoadImageTask loadTask = new LoadImageTask();
            loadTask.execute(currentPath);  //异步载入图片
        }
    }

    private int isMusicPlay = 1;//1在播放0停止
    private int isVideoPlay = 1;//1在播放0停止
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_delete:

                final AlertDialog builder = new AlertDialog.Builder(ShowMyArtsActivity.this)
                        .setMessage("确认删除吗？").setCancelable(false).setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //执行解绑操作,并跳转登录界面
                                        if (mMediaPlayer!=null){
                                            mMediaPlayer.pause();
//                                            mMediaPlayer.release();
                                            //停止播放音乐，停止动画
                                            stopCDAni();
                                        }
                                        if (mode!=null && mode.equals("myartlist")){ //返回myartlist页面后删除
                                            Intent intent = new Intent();
                                            intent.putExtra("position",position);
                                            setResult(RESULT_OK,intent);
                                            finish();
                                        }else { //立即从litepal中删除
                                            if (create_time!=null && create_time.length()>0){
                                                LitePal.deleteAll(MyArt.class, "create_time =?", create_time);
                                                Toast.makeText(ShowMyArtsActivity.this, "作品已删除", Toast.LENGTH_SHORT).show();
                                            }

                                            finish();
                                        }


                                    }
                                })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();
                //修改 确定取消 按钮的字体大小
                builder.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.theme_color));
                builder.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.theme_color));


                break;
            case R.id.btn_share:
                Log.i("第三方分享","type====="+type);
                MyUtils.shareToThirdApp(ShowMyArtsActivity.this,currentPath,type);
                break;
            case R.id.tv_art_list:
                startActivity(new Intent(ShowMyArtsActivity.this, MyArtListActivity.class));
                finish();
                break;
            case R.id.iv_photo:
                if (isMusicPlay == 1){
                    isMusicPlay = 0 ;
                    //停止播放音乐，停止动画
                    mMediaPlayer.pause();
                    stopCDAni();
                }else if (isMusicPlay == 0){
                    isMusicPlay = 1 ;
                    //停止播放音乐，停止动画
                    mMediaPlayer.start();
                    playCDAni();
                }

                break;
            case R.id.layout02:
                if (isVideoPlay == 1){
                    isVideoPlay = 0 ;
                    //停止播放音乐，停止动画
                    videoView.pause();
                    iv_video_click.setImageResource(R.mipmap.jz_play_pressed);
                    iv_video_click.setVisibility(View.VISIBLE);
                }else if (isVideoPlay == 0){
                    isVideoPlay = 1 ;
                    //停止播放音乐，停止动画
                    videoView.start();
                    iv_video_click.setImageResource(R.mipmap.jz_pause_pressed);
                    iv_video_click.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            iv_video_click.setVisibility(View.INVISIBLE);
                        }
                    },1200);

                }


                break;
        }
    }

    private void shareImg(Bitmap bitmap) { //分享二维码
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("image/*");//设置分享内容的类型
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent = Intent.createChooser(intent, R.string.menu_share+"");
        startActivity(intent);
    }


    /**
     * 这个方法是为了获取图片的，异步获取图片方法
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapUtils.getSampledBitmap(params[0],
                    imageWidth / 4, imageHeight / 4);
//            return BitmapUtils.getSampledBitmap(params[0],//区别不是很大`
//                    imageWidth, imageHeight);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (mainBitmap != null) {
                mainBitmap.recycle();
                mainBitmap = null;
                System.gc();
            }
            mainBitmap = result;
            imgView.setImageBitmap(mainBitmap);  //mainActivity中三个按钮上方的图片框
        }
    }

    private void playCDAni(){
        Log.i(TAG, "playCDAni ===" + System.currentTimeMillis());
        if(iv_photo.getAnimation()==null){
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.music_cd);
            LinearInterpolator lin = new LinearInterpolator();
            animation.setInterpolator(lin);
            iv_photo.startAnimation(animation);
        }
    }

    private void stopCDAni(){
        if(iv_photo.getAnimation()!=null){
            iv_photo.clearAnimation();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mMediaPlayer!=null){
            iv_photo.post(new Runnable() { //防止被广告打断音频播放
                @Override
                public void run() {
                    mMediaPlayer.start();
                }
            });

        }
        MobclickAgent.onPageStart("ShowMyArtsActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("ShowMyArtsActivity");//统计页面
        MobclickAgent.onPause(this);
        if (mMediaPlayer!=null){
            mMediaPlayer.pause();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTTAd != null) {
            mTTAd.destroy();
        }
        if (mMediaPlayer!=null){
            mMediaPlayer.release();
        }
    }
}
